﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Project.MVC.Model;
using Project.MVC.Service;
using Project.MVC.Web.Models.Grid;
using Project.MVC.Web.Helper.jqGrid;
namespace Project.MVC.Web.Areas.QuanLy.Controllers
{
    public class CategoryController : Controller
    {
        #region Services
        private readonly ICategoryServices services;

        public CategoryController()
            : this(new CategoryServices()
            )
        {
        }

        public CategoryController(ICategoryServices iservices

            )
        {
            services = iservices;

        }
        #endregion
        public ActionResult Index()
        {
            return View("Index");
        }
        public ActionResult Add()
        {
            var viewModel = new CategoryInfo();
            return View("Add",viewModel);
        }
        [HttpPost]
        public ActionResult Add(CategoryInfo category, FormCollection form)
        {
            getInfo(category, form, false);
            services.Insert(category);
            //service.SaveChange();
            //end add
            return View("Edit", category);
        }
        public ActionResult Edit(int id)
        {
            var model = services.GetByKey(id);
            return View("Edit", model);
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Edit(CategoryInfo cate, FormCollection form)
        {
            getInfo(cate, form, true);
            services.Update(cate);
            services.SaveChange();
            return View("Edit", cate);
        }
        #region Ajax and Json methods
        public JsonResult GetList(GridSettings grid)
        {

            IQueryable<CategoryInfo> list = null;
            list = services.GetList2Grid();
            //THIẾT LẬP JQUERY GRID
            list = JqGrid.SetupGrid<CategoryInfo>(grid, list);

            return Json(list.ToJqGridData(grid.PageIndex, grid.PageSize, null, null, null), JsonRequestBehavior.AllowGet);
        }
        #endregion
        #region Private methods
        private void getInfo(CategoryInfo value, FormCollection form, bool isUpdate)
        {
            if (form == null) return;
            if (value == null) value = new CategoryInfo();           
            value.Title = form.Get(CategoryInfo.ListFieldName.Title);
            value.ParentId = null;
            if (isUpdate)
            {
                value.Id = int.Parse(form.Get(CategoryInfo.ListFieldName.Id));
            }
        }

        #endregion
    }
}
